<template>
    <view>
        <view class="top">
            <view class="">
                <navigator url="/pages/index/index" open-type="switchTab">
                    <image class="back" src="/static/images/白色左箭头.png" mode=""></image>
                </navigator>
                <view class="title">
                    专业洗车
                </view>
            </view>
            <view class="ss">
                <input class="in" type="text" placeholder="搜索商家" @input="searchMerchant" />
                <image class="sx" src="/static/images/搜索.png" mode=""></image>
            </view>
        </view>
        <view class="body">
            <!-- 加载中提示 -->
            <view v-if="isLoading" class="loading-state">
                <uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
            </view>
            
            <!-- 商家列表 -->
            <uni-card 
                v-else
                v-for="merchant in merchantList" 
                :key="merchant.id" 
                class="card" 
                :title="merchant.name" 
                :extra="merchant.distance ? merchant.distance : '未知距离'" 
                :is-shadow="false"
            >

                <navigator :url="'/pages/yonghu1/xichedian/xichedian?merchantId=' + merchant.id + '&merchantImage=' + encodeURIComponent(merchant.image)">
                    <view class="text">
                        <image class="image" :src="merchant.image" mode="aspectFill"></image>
                        <view class="wz">
                            <view class="info-item">
                                <text class="label">营业时间：</text>
                                <text>{{merchant.startTime}} - {{merchant.endTime}}</text>
                            </view>
                            <view class="info-item">
                                <text class="label">地址：</text>
                                <text>{{merchant.address}}</text>
                            </view>
                        </view>
                    </view>
                </navigator>
            </uni-card>
            
            <!-- 无数据时显示 -->
            <view v-if="!isLoading && merchantList.length === 0" class="empty-state">
                暂无商家信息
            </view>
        </view>
    </view>
</template>

<script>
import request from '../../../uitls/request';

export default {
    data() {
        return {
            merchantList: [],
            searchKeyword: '',
            allMerchants: [], // 存储所有商家信息
            userLatitude: null,
            userLongitude: null,
            isLoading: true, // 添加加载状态
            loadingText: {
                contentdown: '上拉显示更多',
                contentrefresh: '正在加载...',
                contentnomore: '没有更多数据了'
            }
        }
    },
    methods: {
        // 获取当前位置
        getCurrentLocation() {
            uni.getLocation({
                type: 'wgs84', // preferred coordinate system
                success: (res) => {
                    console.log('当前位置的经纬度：', res.latitude, res.longitude);
                    this.userLatitude = res.latitude;
                    this.userLongitude = res.longitude;
                    // After getting location, fetch merchants
                    this.getMerchantList();
                },
                fail: (err) => {
                    console.error('获取位置失败:', err);
                    uni.showToast({
                        title: '获取位置失败，部分功能可能受限',
                        icon: 'none'
                    });
                    // Still try to get merchant list even if location fails
                    this.getMerchantList();
                }
            });
        },
        // 计算两个经纬度之间的距离（单位：米）
        calculateDistance(lat1, lon1, lat2, lon2) {
            const R = 6371e3; // metres
            const φ1 = lat1 * Math.PI / 180; // φ, λ in radians
            const φ2 = lat2 * Math.PI / 180;
            const Δφ = (lat2 - lat1) * Math.PI / 180;
            const Δλ = (lon2 - lon1) * Math.PI / 180;

            const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
                      Math.cos(φ1) * Math.cos(φ2) *
                      Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

            const d = R * c; // in metres
            return d;
        },
        // 获取商家列表
        getMerchantList() {
            this.isLoading = true; // 开始加载
            // 首先获取所有商家信息
            request({
                url: '/xsc/merchant/list',
                method: 'GET',
                data: {
                    pageNum: 1,
                    pageSize: 100
                },
                success: (res) => {
                    console.log('商家列表接口返回数据:', res.data);
                    if (res.data.code === 200) {
                        this.allMerchants = res.data.rows;
                        console.log('所有商家信息:', this.allMerchants);
                        // 获取专业洗车商家列表
                        this.getSpecializedMerchants();
                    }
                },
                fail: (err) => {
                    this.isLoading = false; // 加载失败时也要关闭加载状态
                    console.error('请求失败:', err);
                    uni.showToast({
                        title: '网络请求失败',
                        icon: 'none'
                    });
                }
            });
        },

        // 获取专业洗车商家列表
        getSpecializedMerchants() {
            request({
                url: '/xsc/type/merchants/专业洗车',
                method: 'GET',
                success: (res) => {
                    console.log('专业洗车商家接口返回数据:', res.data);
                    if (res.data.code === 200) {
                        const rawMerchants = Array.isArray(res.data.data) ? res.data.data : [];
                        console.log('专业洗车商家原始数据:', rawMerchants);
                        
                        // 映射数据结构并合并商家信息
                        const processedMerchants = rawMerchants.map(item => {
                            // 在allMerchants中查找对应的商家信息
                            const merchantInfo = this.allMerchants.find(m => m.id === item.merchantId);
                            
                            console.log('商家信息:', merchantInfo);
                            console.log('开始时间:', merchantInfo?.startTime);
                            console.log('结束时间:', merchantInfo?.endTime);
                            
                            // 处理营业时间
                            let startTimeDisplay = '未知日期';
                            let endTimeDisplay = '未知日期';

                            if (merchantInfo) {
                                // 处理开始时间
                                if (merchantInfo.startTime) {
                                    const startDate = new Date(merchantInfo.startTime);
                                    // Check if date is valid before formatting
                                    if (!isNaN(startDate.getTime())) {
                                        const year = startDate.getFullYear();
                                        const month = String(startDate.getMonth() + 1).padStart(2, '0'); // Month is 0-indexed
                                        const day = String(startDate.getDate()).padStart(2, '0');
                                        startTimeDisplay = `${year}-${month}-${day}`;
                                    }
                                }

                                // 处理结束时间
                                if (merchantInfo.endTime) {
                                    const endDate = new Date(merchantInfo.endTime);
                                     // Check if date is valid before formatting
                                    if (!isNaN(endDate.getTime())) {
                                        const year = endDate.getFullYear();
                                        const month = String(endDate.getMonth() + 1).padStart(2, '0'); // Month is 0-indexed
                                        const day = String(endDate.getDate()).padStart(2, '0');
                                        endTimeDisplay = `${year}-${month}-${day}`;
                                    }
                                }
                            }
                            
                            console.log('处理后的开始时间:', startTimeDisplay);
                            console.log('处理后的结束时间:', endTimeDisplay);
                            
                            return {
                                id: item.merchantId,
                                name: item.merchantName,
                                address: item.merchantAddress,
                                rate: item.rate || 0,
                                startTime: startTimeDisplay,
                                endTime: endTimeDisplay,
                                image: item.merchantImage || '/static/images/default-merchant.png',
                                distance: item.distance
                            };
                        });

                        // Calculate distance for each merchant
                        if (this.userLatitude !== null && this.userLongitude !== null) {
                            this.merchantList = processedMerchants.map(merchant => {
                                const merchantInfo = this.allMerchants.find(m => m.id === merchant.id);
                                if (merchantInfo && merchantInfo.latitude && merchantInfo.longitude) {
                                    const distance = this.calculateDistance(
                                        this.userLatitude,
                                        this.userLongitude,
                                        merchantInfo.latitude,
                                        merchantInfo.longitude
                                    );
                                    // Convert meters to kilometers and format to 2 decimal places
                                    const distanceInKm = (distance / 1000).toFixed(2);
                                    return { ...merchant, distance: `${distanceInKm}km` }; // Add formatted distance in km
                                } else {
                                    return { ...merchant, distance: null }; // No location info for merchant
                                }
                            });
                        } else {
                             // If user location is not available, just use processed merchants
                            this.merchantList = processedMerchants;
                        }

                        console.log('最终的商家列表 (包含距离):', this.merchantList);
                        this.isLoading = false; // 数据加载完成，关闭加载状态
                    } else {
                        this.isLoading = false; // 请求失败时关闭加载状态
                        uni.showToast({
                            title: res.data.msg || '获取商家列表失败',
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    this.isLoading = false; // 请求失败时关闭加载状态
                    console.error('请求失败:', err);
                    uni.showToast({
                        title: '网络请求失败',
                        icon: 'none'
                    });
                }
            });
        },
        
        // 搜索商家
        searchMerchant(e) {
            this.searchKeyword = e.detail.value.trim();
            if (!this.searchKeyword) {
                this.getMerchantList();
                return;
            }
            
            // 本地搜索
            const filteredList = this.merchantList.filter(item => 
                item.name.includes(this.searchKeyword) || 
                (item.address && item.address.includes(this.searchKeyword))
            );
            this.merchantList = filteredList;
        }
    },
    onLoad() {
        // Get current location first, then fetch merchants
        this.getCurrentLocation();
    }
}
</script>

<style scoped>
    .top {
        width: 100%;
        padding-bottom: 40px;
        background-image: url('../../../static/images/组 8.png');
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center;
    }

    .top .back {
        position: absolute;
        margin-left: 20px;
        margin-top: 30px;
        width: 15px;
        height: 15px;
        z-index: 2;
    }

    .top .title {
        text-align: center;
        font-size: 18px;
        color: #fff;
        line-height: 44px;
        padding-top: 20px;
    }

    .body {
        margin-top: -40px;
    }

    .ss {
        display: flex;
        margin: 20px;
        background-color: white;
        height: 30px;
        border-radius: 15px;
        line-height: 20px;
    }

    .ss .sx {
        position: absolute;
        right: 40px;
        margin-top: 8px;
        width: 15px;
        height: 15px;
    }

    .ss .in {
        margin-top: 5px;
        margin-left: 20px;
        width: 70%;
    }


    .card {
        border-radius: 10px;
    }

    .text {
        margin-top: 20px;
        display: flex;
    }

    .text .image {
        width: 80px;
        height: 80px;
        margin-right: 10px;
    }

    .body .pf {
        display: flex;
    }

    .card .wz {
        width: 70%;
    }

    .empty-state {
        text-align: center;
        padding: 40px 0;
        color: #999;
        font-size: 14px;
    }

    .rate-text {
        margin-left: 10px;
        color: #FF7500;
        font-size: 14px;
    }

    .info-item {
        margin-bottom: 8px;
        font-size: 14px;
        color: #666;
    }

    .label {
        color: #999;
        margin-right: 5px;
    }

    .card {
        margin-bottom: 15px;
    }

    .text .image {
        border-radius: 8px;
    }

    .loading-state {
        padding: 20px 0;
        text-align: center;
    }
</style>